package vars

import java.sql.ResultSet
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.mbari.vars.dao.ObjectDAO
import org.mbari.vars.knowledgebase.model.dao.ConceptDAO

class DAO {
    
    private static final log = LoggerFactory.getLogger(DAO.class)

    /**
     * Executes a query to the database.
     *
     * @param sql The SQL string use for the query
     * @param resultSetHandler A Closure that processes the resultSet returned 
     *      by the SQL
     * @return Whatever the closure returns
     */
    static query(String sql, Closure resultSetHandler) {
        def db = ObjectDAO.fetchDatabase()
        db.begin()
        def connection = db.getJdbcConnection()
        def statement = connection.createStatement()
        log.debug(sql)
        ResultSet resultSet = statement.executeQuery(sql);
        def data = resultSetHandler(resultSet)
        resultSet.close()
        statement.close()
        db.commit()
        db.close()
        return data
    }
    
    static void expireCache() {
        try {
            def database = ObjectDAO.fetchDatabase()
            def cacheManager = database.getCacheManager();
            cacheManager.expireCache();
            database.close()
        }
        catch (Exception e) {
            log.error("Failed to clear Castor's cache", e)
        }
    }
    
    static ancestorsAsList(String conceptName) {
        def ancestors = []
        def concept = ConceptDAO.instance.findByName(conceptName)
        while (concept) {
            ancestors << concept
            concept = concept.parentConcept
        }
        return ancestors.reverse()
    }

}